package com.wjm.filter;


import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/*@Component
@WebFilter(filterName="Servlet3Filter",urlPatterns="/test")*/
public class IPFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.print("进入filter");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String IP = getIp(request);
        System.out.println("进入Filter");

        HttpSession session  = request.getSession();
        Map<String,Integer> map  = (Map) session.getAttribute("key");
            try {
                Integer index =  map.get(IP);
                index++;
                map.put(IP,index);
                System.out.println("IP："+IP+" 第"+index+"访问");
            }catch (NullPointerException e) {
                map.put(IP,1);
                System.out.println("初次访问");

            }



    }

    @Override
    public void destroy() {

    }


    public String getIp(HttpServletRequest request) {
        String remoteAddr = request.getRemoteAddr();
        String forwarded = request.getHeader("X-Forwarded-For");
        String realIp = request.getHeader("X-Real-IP");
        String ip = null;
        if (realIp == null) {
            if (forwarded == null) {
                ip = remoteAddr;
            } else {
                ip = remoteAddr + "/" + forwarded.split(",")[0];
            }
        } else {
            if (realIp.equals(forwarded)) {
                ip = realIp;
            } else {
                if(forwarded != null){
                    forwarded = forwarded.split(",")[0];
                }
                ip = realIp + "/" + forwarded;
            }
        }
        return  ip;

    }
}
